<script setup lang="ts">
import { Secret } from "@/views/domain/kubeHud/api/k8s/types";
import { reactive } from "vue";

type DockerConfigType = {
  auths: {
    [key: string]: {
      username: string;
      password: string;
      auth?: string;
      email?: string;
    };
  };
};

const data = defineModel<Secret>();
const key = ".dockerconfigjson";
const editForm = reactive({
  schema: "https://",
  address: "",
  username: "",
  password: "",
  email: ""
});

const syncToData = () => {
  const cfg: DockerConfigType = {
    auths: {
      [`${editForm.schema}${editForm.address}`]: {
        username: editForm.username,
        password: editForm.password,
        email: editForm.email,
        auth: btoa(`${editForm.username}:${editForm.password}`)
      }
    }
  };

  data.value[key] = btoa(JSON.stringify(cfg));
};

const rules = reactive({
  address: [{ required: true, message: "请输入镜像地址", trigger: "blur" }],
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }]
});
</script>

<template>
  <div class="flex flex-col gap-4">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="镜像地址" :rules="rules.address">
          <el-input v-model="editForm.address" @change="syncToData">
            <template #prepend>
              <el-select v-model="editForm.schema" style="width: 100px">
                <el-option label="http://" value="http://" />
                <el-option label="https://" value="https://" />
              </el-select>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="用户名" :rules="rules.username">
          <el-input v-model="editForm.username" @change="syncToData" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" @change="syncToData" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="密码" :rules="rules.password">
          <el-input
            v-model="editForm.password"
            type="password"
            show-password
            @change="syncToData"
          />
        </el-form-item>
      </el-col>
    </el-row>
  </div>
</template>
<style lang="scss" scoped></style>
